package com.mybatisflex.admin.util;

import com.mybatisflex.core.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author michael
 */
public class ImageUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(ImageUtil.class);

    private final static String[] IMG_EXTS = new String[]{"jpg", "jpeg", "png", "bmp"};

    public static String getExtName(String fileName) {
        int index = fileName.lastIndexOf('.');
        if (index != -1 && (index + 1) < fileName.length()) {
            return fileName.substring(index + 1);
        } else {
            return null;
        }
    }

    /**
     * 过文件扩展名，判断是否为支持的图像文件
     *
     * @param fileName
     * @return 是图片则返回 true，否则返回 false
     */
    public static boolean isImage(String fileName) {
        if (StringUtil.isBlank(fileName)) {
            return false;
        }
        fileName = fileName.trim().toLowerCase();
        String ext = getExtName(fileName);
        if (ext != null) {
            for (String s : IMG_EXTS) {
                if (s.equalsIgnoreCase(ext)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 通过文件名判断
     * @param fileName
     */
    public static boolean notImage(String fileName) {
        return !isImage(fileName);
    }


    public static String saveImage(MultipartFile mf) throws IOException {
        ImageUtil.ImageFile imageFile = ImageUtil.newImageFileSameExt(mf.getOriginalFilename());
        mf.transferTo(imageFile.file);
        return imageFile.path;
    }


    public static ImageFile newImageFileSameExt(String fileName){
        return newImageFile(getExtName(fileName));
    }


    public static ImageFile newImageFile(String extName){
        ImageFile imageFile = new ImageFile();
        imageFile.path = "/avatars/"
                + DateUtil.toDateString(new Date()) + "/"
                + UUID.randomUUID() + "." + extName;
        ClassPathResource fileResource = new ClassPathResource("/");
        try {
            File file = new File(fileResource.getFile(), "/public"+imageFile.path);
            if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
                LOGGER.error("Can not mkdirs: " + file.getParentFile());
            }
            imageFile.file = file;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageFile;
    }


    public static class ImageFile{
        public String path;
        public File file;
    }

}
